/*
 * @lc app=leetcode.cn id=59 lang=typescript
 *
 * [59] 螺旋矩阵 II
 */

// @lc code=start
function generateMatrix(n: number): number[][] {
  const DIRECTION = [
    [0, 1],
    [1, 0],
    [0, -1],
    [-1, 0],
  ]
  const matrix = new Array(n).fill(0).map(() => new Array(n).fill(0))
  let [top, bottom, left, right] = [0, n - 1, 0, n - 1]
  let [i, j, d, num] = [0, 0, 0, 1]
  while (num <= n * n) {
    matrix[i][j] = num++
    if (i < top || i > bottom || j < left || j > right) {
      switch (d) {
        case 0:
          top++
          break
        case 1:
          right--
          break
        case 2:
          bottom--
          break
        case 3:
          left++
          break
      }
      d = (d + 1) % 4
    }
    i += DIRECTION[d][0]
    j += DIRECTION[d][1]
  }
  return matrix
}
// @lc code=end
